<template>
  <div>
    <el-dialog
      title="添加分类"
      :visible.sync="Diashows"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="ruleForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="value"
            :options="data"
            :props="expandTrigger"
            clearable
            change-on-select
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="dialogVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        cat_name: "",
        cat_pid: "",
        cat_level: "",
      },
      rules: {
        cat_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      value: [],
      expandTrigger: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
    };
  },
  props: {
    Diashows: {
      type: Boolean,
      defaule: true,
    },
    data: {
      type: Array,
      defaule: true,
    },
  },
  watch: {
    data: function (newval, oldval) {
      console.log(newval);
      this.$nextTick(() => {
        document.getElementsByClassName("el-cascader-panel")[0].style.height =
          "200px";
      });
    },
  },
  mounted() {},
  methods: {
    //确定
    dialogVisible() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        this.$axios.post("categories", this.ruleForm).then((res) => {
          console.log(res);
          if (res.data.meta.status == 201) {
            this.$message({
              message: res.data.meta.msg,
              type: "success",
            });
            this.$emit('updata');
                  this.ruleForm.cat_name = "";
      this.value = [];
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: "error",
            });
          }
        });
              
        this.$emit("closeDiag");
   
      });
    },
    handleClose() {
      this.ruleForm.cat_name = "";
      this.value = [];
      this.$emit("closeDiag");
    },
    handleChange(val) {
      if (this.value.length > 0) {
        this.ruleForm.cat_pid = this.value[this.value.length - 1];
        this.ruleForm.cat_level = this.value.length;
      } else {
        this.ruleForm.cat_pid = 0;
        this.ruleForm.cat_level = 0;
      }
    },
  },
};
</script>
<style scoped>
</style>